const router = require("express").Router();
const db = require("../models");
const crypt = require("../tools/crypt");
const jwt = require("jsonwebtoken");
const svgCaptcha = require("svg-captcha");
const multer = require("multer");

//validation
const Joi = require("@hapi/joi");

const loginSchema = Joi.object({
  phone: Joi.string().pattern(new RegExp("^1[3456789]\\d{9}$")),
  password: Joi.string().pattern(new RegExp("^[a-zA-Z0-9_]{6,30}$")),
  captcha: Joi.string().pattern(new RegExp("^[a-zA-Z0-9]{4}$")),
});

//验证码设置
const codeConfig = {
  size: 4,
  ignoreChars: "0o1i",
  noise: 4,
  height: 47,
  color: true,
  background: "white",
};

//全局验证码对象，方便登录的时候验证
let captcha = { text: "test" };

router.get("/captcha", (req, res) => {
  //创建验证码
  captcha = svgCaptcha.create(codeConfig);

  //返回验证码的svg
  res.send(captcha.data);
});

const upload = multer(); //处理formdata
router.post("/", upload.none(), async (req, res, next) => {
  // console.log(req.body)
  console.log(req.ip + " try to login with captcha " + captcha.text);

  const { error, value } = loginSchema.validate(req.body);

  if (error) {
    res.status(400).send({ msg: error.message });
  } else if (value.captcha.toLowerCase() !== captcha.text.toLowerCase()) {
    //比对验证码
    res.status(400).send({ msg: "验证码错误！" });
  } else {
    const user = await db.Staff.findOne({
      where: { staff_phone: value.phone },
    });

    if (!user) {
      res.status(400).send({ msg: "用户不存在！" });
    } else {
      // console.log(user)
      const passwordCorrect = crypt.correct(value.password, user.password);

      if (passwordCorrect) {
        const token = jwt.sign(
          { id: user.id, department: user.department_id, level: user.level },
          process.env.TOKEN_SECRET,
          { expiresIn: "1d" }
        );
        const clientUser = {
          name: user.staff_name,
          email: user.staff_email,
          tel: user.staff_phone,
          department: user.department_id,
          id: user.id,
          level: user.level,
        };
        res.send({ msg: "登录成功！", token: token, user: clientUser });
      } else {
        res.status(400).send({ msg: "密码错误！" });
      }
    }
  }
  captcha = svgCaptcha.create(codeConfig);
});

module.exports = router;
